﻿using B.S.Production.ErrorCode;
using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using Warehouse.Domain;
using Warehouse.ErrorCord;
using Warehouse.Read.Api.Actions.Command.WarehouseCategory;

namespace Warehouse.Read.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DoaController : ControllerBase
    {
        private readonly ISqlSugarClient db;
        private readonly IMediator mediator;

        public DoaController(ISqlSugarClient db, IMediator mediator)
        {
            this.db = db;
            this.mediator = mediator;
        }




        /// <summary>
        /// 导入仓库管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "仅支持上传 Excel 文件"; 
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<WarehouseInformation> inventoriesList = new List<WarehouseInformation>();

                        foreach (var row in rows)
                        {
                            string stateValue = row.Cell(4).GetValue<string>();
                            StatesNum stateEnum;
                            // 尝试解析状态值，若失败则默认指定一个值
                            if (!Enum.TryParse(stateValue, out stateEnum))
                            {
                                stateEnum = StatesNum.Reviewed; // 使用默认状态（需确保 `StatesNum` 中有此项）
                            }

                            var inventory = new WarehouseInformation()
                           ;
                            inventory.WarehouseId = row.Cell(1).GetValue<int>();
                            inventory.MyPropertylogid = row.Cell(2).GetValue<string>();
                            inventory.WarehouseName = row.Cell(3).GetValue<string>();
                            inventory.WarehouseTypeId = row.Cell(4).GetValue<int>();
                            inventory.WarehouseAdder = row.Cell(5).GetValue<string>();
                            inventory.WarehouseRemark = row.Cell(6).GetValue<string>();
                            inventory.CreateTime = DateTime.Now;//new DateTime(Convert.ToInt32( row.Cell(7).GetValue<string>().Split('-')[0]));
                            


                            // 添加到要插入的列表中
                            inventoriesList.Add(inventory);
                        }

                        // 将数据批量插入数据库
                        await db.Insertable(inventoriesList).ExecuteCommandAsync();

                        result.Code = APIEnum.Success;
                        result.Msg = "导入成功";
                        result.Data = inventoriesList.Count;
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }

        /// <summary>
        /// 导入仓库类别管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportType(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<Warehouse.Domain.WarehouseCategory> inventoriesList = new List<Warehouse.Domain.WarehouseCategory>();

                        foreach (var row in rows)
                        {
                            string stateValue = row.Cell(4).GetValue<string>();
                            StatesNum stateEnum;
                            // 尝试解析状态值，若失败则默认指定一个值
                            if (!Enum.TryParse(stateValue, out stateEnum))
                            {
                                stateEnum = StatesNum.Reviewed; // 使用默认状态（需确保 `StatesNum` 中有此项）
                            }

                            var inventory = new Warehouse.Domain.WarehouseCategory();
                            inventory.WarehouseTypeId = row.Cell(1).GetValue<int>();
                            inventory.WarehouseTypeName = row.Cell(2).GetValue<string>();
                            inventory.WarehouseTypeLogid = row.Cell(3).GetValue<string>();
                            inventory.ParentId = row.Cell(4).GetValue<int>();
                            //inventory.WarehouseTypeId = row.Cell(4).GetValue<int>();
                            //inventory.WarehouseAdder = row.Cell(5).GetValue<string>();
                            //inventory.WarehouseRemark = row.Cell(6).GetValue<string>();
                            //inventory.CreateTime = DateTime.Now;//new DateTime(Convert.ToInt32( row.Cell(7).GetValue<string>().Split('-')[0]));



                            // 添加到要插入的列表中
                            inventoriesList.Add(inventory);
                        }

                        // 将数据批量插入数据库
                        await db.Insertable(inventoriesList).ExecuteCommandAsync();

                        result.Code = APIEnum.Success;
                        result.Msg = "导入成功";
                        result.Data = inventoriesList.Count;
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }

        /// <summary>
        /// 查询仓库类别全部数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<Warehouse.Domain.WarehouseCategory>>> GetHandle([FromQuery]GetTypeShowCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 导出仓库类别管理
        /// </summary> 
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportOrderListTypesExcel([FromQuery] GetTypeShowCommand command)
        {
            try
            {

                var list = (await GetHandle(command)).Data;
                IWorkbook wb = new XSSFWorkbook();
                //在创建的Excel文件中创建一个工作表
                ISheet sheet = wb.CreateSheet("仓库信息表");
                //在创建的工作表中创建一行
                //注意行的序号
                IRow row = sheet.CreateRow(0);
                //在行中创建单元格 在单元格中写值
                row.CreateCell(0).SetCellValue("仓库类别编号");
                row.CreateCell(1).SetCellValue("仓库类别名称");
                row.CreateCell(2).SetCellValue("仓库类别id");
                row.CreateCell(3).SetCellValue("父级id");
                

                //写订单信息
                //行编号
                int index = 1;
                foreach (var item in list)
                {
                    //创建新行
                    row = sheet.CreateRow(index);
                    //在行中创建单元格
                    row.CreateCell(0).SetCellValue(item.WarehouseTypeId);
                    row.CreateCell(1).SetCellValue(item.WarehouseTypeName);
                    row.CreateCell(2).SetCellValue(item.WarehouseTypeLogid);
                    row.CreateCell(3).SetCellValue(item.ParentId);
                    

                    //换行
                    index++;
                }
                //导出
                //excel
                byte[] buffer;
                //使用内存流出Excel的内容
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                //excel mine
                string excelMine = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                return File(buffer, excelMine, "仓库类别信息表.xlsx");
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 查询仓库全部数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<WarehouseInformation>>> getShow([FromQuery]GetShowCommand request)     
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 导出仓库管理
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportOrderListToExcel([FromQuery] GetShowCommand command)
        {
            try
            {

                var list = (await getShow(command)).Data;
                IWorkbook wb = new XSSFWorkbook();
                //在创建的Excel文件中创建一个工作表
                ISheet sheet = wb.CreateSheet("仓库信息表");
                //在创建的工作表中创建一行
                //注意行的序号
                IRow row = sheet.CreateRow(0);
                //在行中创建单元格 在单元格中写值
                row.CreateCell(0).SetCellValue("仓库编号");
                row.CreateCell(1).SetCellValue("仓库编号id");
                row.CreateCell(2).SetCellValue("仓库名称");
                row.CreateCell(3).SetCellValue("所属类别");
                row.CreateCell(4).SetCellValue("仓库地址");
                row.CreateCell(5).SetCellValue("备注");
                row.CreateCell(6).SetCellValue("创建时间");
                
                //写订单信息
                //行编号
                int index = 1;
                foreach (var item in list)
                {
                    //创建新行
                    row = sheet.CreateRow(index);
                    //在行中创建单元格
                    row.CreateCell(0).SetCellValue(item.WarehouseId);
                    row.CreateCell(1).SetCellValue(item.MyPropertylogid);
                    row.CreateCell(2).SetCellValue(item.WarehouseName);
                    row.CreateCell(3).SetCellValue(item.WarehouseTypeId);
                    row.CreateCell(4).SetCellValue(item.WarehouseAdder);
                    row.CreateCell(5).SetCellValue(item.WarehouseRemark);
                    row.CreateCell(6).SetCellValue(item.CreateTime.ToString("yyyy-MM-dd"));
                    
                    //换行
                    index++;
                }
                //导出
                //excel
                byte[] buffer;
                //使用内存流出Excel的内容
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                //excel mine
                string excelMine = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                return File(buffer, excelMine, "仓库信息表.xlsx");
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
